package com.example.administrator.testxingpiao.ui.cart;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.testxingpiao.R;
import com.example.administrator.testxingpiao.bean.CartBean;
import com.example.administrator.testxingpiao.dao.CartDao;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;


/**
 * Created by Administrator on 2016/8/10.
 */
public class CartAdapter extends BaseAdapter {
    private boolean[] isChecked;
    private List<CartBean> mList;
    private Handler handler;
    public CartAdapter(List<CartBean> list,Handler handler) {

        this.mList = list;
        isChecked=new  boolean[mList.size()];
        this.handler = handler;
    }
    public void SelectAll(boolean b){
        for (int i=0;i < isChecked.length;i++){
            isChecked[i]=b;
        }
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final Context context = parent.getContext();
        final ViewHolder holder;
        // 获取布局填充器的另一个方法
        if (convertView == null) {
            // 获取布局填充器的另一个方法
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.item_cart_list, null);
            // 要减少findViewById的次数.
            holder = new ViewHolder();
            holder.ivShow = (ImageView) convertView.findViewById(R.id.iv_show);
            holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
            holder.tvPrice = (TextView) convertView.findViewById(R.id.tv_price);
            holder.cbChoose = (CheckBox) convertView.findViewById(R.id.cb_choose);
            holder.etCount = (EditText) convertView.findViewById(R.id.et_count);
            holder.ivSubtract = (ImageView) convertView.findViewById(R.id.iv_subtract);
            holder.ivAdd = (ImageView) convertView.findViewById(R.id.iv_add);
            // 存储holder
            convertView.setTag(holder);
        } else {
            // 取出holder
            holder = (ViewHolder) convertView.getTag();
        }
        holder.cbChoose.setChecked(isChecked[position]);
        //绑定布局
        final CartBean cb = mList.get(position);
        final String price = cb.getPrice();
        holder.tvTitle.setText(cb.getName());
        holder.tvPrice.setText(price);
        holder.etCount.setText(cb.getCount());
        Glide.with(parent.getContext()).load(cb.getImage()).into(holder.ivShow);
        CheckBox cbChoose = holder.cbChoose;
        cbChoose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String count = holder.etCount.getText().toString();
                int changeCount = Integer.parseInt(count);
                cb.setCount(count);
                if(isChecked){
                    sendCartBean(1,price,changeCount,cb);
                }else{
                    sendCartBean(2,price,changeCount,cb);
                }
            }
        });
        holder.ivSubtract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String count = holder.etCount.getText().toString();
                int subCount = Integer.parseInt(count) - 1;
                if(subCount <= 0){
                    subCount = 0;
                    remove();
                }
                holder.etCount.setText(String.valueOf(subCount));
                if(holder.cbChoose.isChecked()){
                    sendPrice(4,price);
                }
                //点击减号，数据库数量减少
                cb.setCount(String.valueOf(subCount));
                int update = CartDao.update(context, cb);
                if(update != -1){
                    Log.i("TAG","数量减少成功！");
                }
            }
            private void remove() {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("删除数据").setMessage("数据为0,是否从购物车移除？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int delete = CartDao.delete(context, cb);
                        if(delete != -1){
                            Message msg = Message.obtain();
                            msg.what = 0;
                            handler.sendMessage(msg);
                        }
                    }
                }).setNegativeButton("否", null).show();
            }
        });
        holder.ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String count = holder.etCount.getText().toString();
                int addCount = Integer.parseInt(count) + 1;
                holder.etCount.setText(String.valueOf(addCount));
                if(holder.cbChoose.isChecked()){
                    sendPrice(3,price);
                }
                //点击加号，数量增加成功！
                cb.setCount(String.valueOf(addCount));
                int update = CartDao.update(context, cb);
                if(update != -1){
                    Log.i("TAG","数量增加成功！");
                }
            }
        });

        return convertView;
    }


    static class ViewHolder {
        private CheckBox cbChoose;
        private ImageView ivShow;
        private TextView tvTitle;
        private TextView tvPrice;
        private EditText etCount;
        private ImageView ivSubtract, ivAdd;

    }
    private void sendCartBean(int what,String sendPrice,int sendCount,CartBean cb){
        Message msg = Message.obtain();
        msg.what = what;

        Double price = Double.parseDouble(sendPrice) * sendCount;
        Bundle bundle = new Bundle();
        bundle.putDouble("price",price);
        msg.setData(bundle);

        msg.obj = cb;
        handler.sendMessage(msg);
    }
    private void sendPrice(int what,String sendPrice){
        Message msg = Message.obtain();
        msg.what = what;
        Double price = Double.parseDouble(sendPrice);
        Bundle bundle = new Bundle();
        bundle.putDouble("price",price);
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

}
